import { useState } from "react";
import { PageContainer, View } from "@tarojs/components";
import Taro, { useRouter } from "@tarojs/taro";
import { useCreation, useResetState } from "ahooks";

import ByCol from "@/components/ui/ByCol";
import ByRow from "@/components/ui/ByRow";
import ByTag from "@/components/ui/ByTag";
import Page from "@/components/common/Page";
import ByText from "@/components/ui/ByText";
import Card from "@/components/common/Card";
import ByCell from "@/components/ui/ByCell";
import PopupPic from "./components/PopupPic";
import ByButton from "@/components/ui/ByButton";
import PopupDelay from "./components/PopupDelay";
import PopupConfirm from "./components/PopupConfirm";
import ByImageGroup from "@/components/ui/ByImageGroup";

import useFetch from "@/hooks/useFetch";
import ApiBudget from "@/api/budget";

/**
 * BillMasterDetail
 */
export interface BillMasterDetail {
  billMasterID: number;
  billNo: string;
  billType: number;
  budgetListId: number;
  buyMoney: number;
  buyNum: number;
  buyPrice: number;
  buyToStockRate: number;
  buyUnit: string;
  isMBPAccept: boolean;
  isValuation: boolean;
  materialCode: string;
  materialID: number;
  materialName: string;
  mbpAcceptDate: string;
  mbpInstallNum: number;
  mbpInStallStaus: number;
  orgCode: string;
  orgName: string;
  outStockId: number;
  outStockName: string;
  pics: string[];
  remark: string;
  saleMoney: number;
  saleNum: number;
  salePrice: number;
  saleToStockRate: number;
  saleUnit: string;
  spec: string;
  stockMoney: number;
  stockNum: number;
  stockPrice: number;
  unit: string;
  workCheckedDelayDate: string;
  workCheckedDelayReason: string;
  workCheckedDelayUserId: number;
  workCheckedDelayUserName: string;
  workCheckedRemark: string;
  /**
   * 工长确认状态 0 未确认 1 部分确认 2 全部确认
   */
  workCheckedStatus: number;
  workerCheckedDate: string;
  workerCheckedNum: number;
  [property: string]: any;
}

const statusMap = {
  0: { label: "待确认", color: "error" },
  1: { label: "部分确认", color: "warning" },
  2: { label: "到货", color: "success" },
};

const btnList = [
  { text: "上传图片", color: "primary", type: "pic" },
  { text: "延迟确认", color: "error", type: "delay" },
  { text: "部分确认", color: "warning", type: "confirmPartial" },
  { text: "全部确认", color: "success", type: "all" },
] as const;

const Item = ({
  data,
  onPopup,
}: {
  data: BillMasterDetail;
  onPopup: (type: string) => void;
}) => {
  const statusConfig = data ? statusMap[data?.workCheckedStatus] : undefined;

  return (
    <>
      <Card className="m-3">
        <ByRow content="between" align="center">
          <ByCol span={"auto"}>{data?.materialName}</ByCol>

          <ByCol span={"none"}>
            {statusConfig && (
              <ByTag type={statusConfig.color}>{statusConfig.label}</ByTag>
            )}
          </ByCol>
        </ByRow>

        <ByCell label="材料规格">{data?.spec}</ByCell>
        <ByCell label="是否安装">
          {data?.isMBPInStall ? "需要" : "不用"}安装
        </ByCell>

        <ByRow content="between" className="mt-2 bg-page rounded-md p-3">
          <View className="text-center">
            <ByText bold>{data?.saleNum}</ByText>
            <View className="mt-1">
              <ByText type="third" size="sm">
                销售量
              </ByText>
            </View>
          </View>

          <View className="text-center">
            <ByText bold>{data?.buyNum}</ByText>
            <View className="mt-1">
              <ByText type="third" size="sm">
                采购量
              </ByText>
            </View>
          </View>

          <View className="text-center">
            <ByText bold>{data?.workerCheckedNum}</ByText>
            <View className="mt-1">
              <ByText type="third" size="sm">
                确认量
              </ByText>
            </View>
          </View>
        </ByRow>

        <ByCell label="备注" vertical>
          {data?.remark || "无"}
        </ByCell>

        {data?.workCheckedDelayReason && (
          <ByCell label="延迟原因">{data.workCheckedDelayReason}</ByCell>
        )}

        {data?.pics && (
          <ByCell label="图片" vertical>
            <ByImageGroup urls={data?.pics} size={210} />
          </ByCell>
        )}

        {data?.workCheckedStatus != 2 && (
          <ByRow content="between">
            {btnList.map((item) => (
              <ByButton
                round
                size="small"
                variant="outline"
                type={item.color}
                key={item.color}
                onClick={() => onPopup(item.type)}
              >
                {item.text}
              </ByButton>
            ))}
          </ByRow>
        )}
      </Card>
    </>
  );
};

export default () => {
  const { params } = useRouter();
  const billMasterID = Number(params.billMasterID);
  const isAll = params.status == "2";

  // 获取详情
  const { data, refresh } = useFetch<{
    billMasterDetail: BillMasterDetail[];
  }>(ApiBudget.materialConfirmDetail, {
    showLoading: true,
    defaultParams: [{ billMasterID }],
    // onAfter: (res: any) => res.billMasterDetail,
  });

  const hadAllConfirm = useCreation(() => {
    if (data?.billMasterDetail) {
      return data.billMasterDetail.every(
        (item) => item.workCheckedStatus === 2
      );
    }
    return isAll;
  }, [data]);

  const [popupMode, setPopupMode, resetPopupModel] = useResetState<string>("");

  // billDetailID
  const [selected, setSelected] = useState();

  // 弹窗操作成功
  const handleSuccess = () => {
    refresh();
    resetPopupModel();
  };

  const PopupNode =
    popupMode === "pic"
      ? PopupPic
      : popupMode === "delay"
      ? PopupDelay
      : popupMode
      ? PopupConfirm
      : undefined;

  // 一键确认
  const { loading, run: runOneClickConfirm } = useFetch(
    ApiBudget.oneClickConfirm,
    "POST",
    { manual: true, onSuccess: () => refresh() }
  );

  const handleOneClickConfirm = async () => {
    const { confirm } = await Taro.showModal({
      title: "一键确认",
      content: "",
    });

    if (confirm) {
      runOneClickConfirm({ billMasterID });
    }
  };

  return (
    <>
      <Page
        footerSticky
        slotFooter={
          !hadAllConfirm && (
            <ByButton
              size="large"
              loading={loading}
              className="w-2/3"
              onClick={handleOneClickConfirm}
            >
              一键确认
            </ByButton>
          )
        }
      >
        {data?.billMasterDetail.map((item) => (
          <Item
            key={item.billDetailID}
            data={item}
            onPopup={(type) => (
              setSelected(item.billDetailID), setPopupMode(type)
            )}
          />
        ))}
      </Page>

      <PageContainer round show={!!PopupNode} onAfterLeave={resetPopupModel}>
        {PopupNode && (
          <PopupNode
            billDetailId={selected!}
            // @ts-expect-error
            checkType={popupMode === "confirmPartial" ? 2 : 1}
            onCancel={resetPopupModel}
            onSuccess={handleSuccess}
          />
        )}
      </PageContainer>
    </>
  );
};
